/* Copyright 2010 John L. Reilly

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

package com.riq;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.riq.entity.Alert;
import com.riq.entity.Location;
import com.riq.entity.Member;
import com.riq.entity.Tracking;

@SuppressWarnings("serial")
public class TrackingServlet extends HttpServlet {
  private static final Logger log = Logger.getLogger(Tracking.class.getName());

  private Long deptId;
  private Long memberId;
  private Long alertId;
  private Long locationId;
  private String responseType;
  
  private String intent; 
  private String action; 
  
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    doGet(request, response);
  }

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
  
  // -----------------------------------------------------------------------------------------------
  //  HEADER
  // -----------------------------------------------------------------------------------------------

  Cookie[] cookie = request.getCookies();
  deptId = Long.valueOf(ServletUtilities.getCookieValue(cookie, "cvDeptId", "999999999"));
  memberId = Long.valueOf(ServletUtilities.getCookieValue(cookie, "cvMemberId", "999999999"));
  alertId = Long.valueOf(ServletUtilities.getCookieValue(cookie, "cvAlertId", "999999999"));
  locationId = Long.valueOf(ServletUtilities.getCookieValue(cookie, "cvLocId", "999999999"));

  intent = request.getParameter("intent"); 
  action = request.getParameter("action"); 

  // -----------------------------------------------------------------------------------------------
  //  METHOD DIRECTORY
  // -----------------------------------------------------------------------------------------------

    if ("create".equalsIgnoreCase(action)) {
      create(response, request, intent); 
    } else if ("memberForm".equalsIgnoreCase(action)) {
      memberForm(response, request, intent); 
    } else { 
      response.sendRedirect("mainMenu.html"); 
    }
  }
    
  // -----------------------------------------------------------------------------------------------
  //  METHODS
  // -----------------------------------------------------------------------------------------------


  
  private Long checkAlertStatus(HttpServletResponse response, ServletRequest request) {

    PersistenceManager pm = PMF.get().getPersistenceManager();
    Alert a = pm.getObjectById(Alert.class, alertId);
    

    // TODO evaluate performance hit of checking
    if (!a.getstatus().equalsIgnoreCase("active")) {
      try {
        response.sendRedirect("noSuchObject.jsp?errormessage=noactivedeptalerts");
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return a.getid();
  }
  
  
    
  private void getMemberObject(HttpServletResponse response, ServletRequest request) {
    
    PersistenceManager pm = PMF.get().getPersistenceManager();
    Member m = pm.getObjectById(Member.class, memberId);
    if (m == null) {
      try {
        response.sendRedirect("noSuchObject.jsp?errormessage=nomember");
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    if (!m.getdeptId().equals(deptId)) {
      try {
        response.sendRedirect("noSuchObject.jsp?errormessage=memberiddeptidmismatch");
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    m.settargetObjectId(locationId);
    m.settargetObjectType("Location");
    pm.makePersistent(m);        
  }
    
  
  private Member vruSelect(HttpServletResponse response, ServletRequest request) {
    
    String tempVRUtarget = "";
    if ("oneclickYes".equalsIgnoreCase(intent)) {
      tempVRUtarget = "1"; 
      intent = "allLocations";
    } else if ("oneclickNo".equalsIgnoreCase(intent)) {
      tempVRUtarget = "2"; 
      intent = "allLocations"; 
    }
   
    if (tempVRUtarget.equals("1") || tempVRUtarget.equals("2")) {
      PersistenceManager pm = PMF.get().getPersistenceManager();
      String q = " select from " + Location.class.getName() + 
           " where deptId == " + deptId + " && vru == '" + tempVRUtarget + "' ";
      List<Location> locations = (List<Location>) pm.newQuery(q).execute();
      if (locations == null) {
        try {
          response.sendRedirect("noSuchObject.jsp?errormessage=novrus");
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      } 
    locationId = locations.get(0).getid();
    responseType = "memberOneClickYes";
    }
    
    return null;
  }
    
    
  private void create(HttpServletResponse response, ServletRequest request, String intent) {
    
    Long alertId = checkAlertStatus(response, request);
    vruSelect(response, request); 
    
    PersistenceManager pm = PMF.get().getPersistenceManager();
    Tracking t = new Tracking (
        deptId,
        alertId,
        locationId,
        System.currentTimeMillis(),
        null,
        "member",
        memberId,
        null,
        responseType
        );
    pm.makePersistent(t);  
    pm.close();
    
    try {
      response.sendRedirect("reportingPrep?alertId=" + alertId.toString() + 
                            "&deptId=" + deptId.toString() +
                            "&intent=" + intent);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
  }
  
  private void memberForm(HttpServletResponse response, ServletRequest request, 
          String intent) {
    
    PersistenceManager pm = PMF.get().getPersistenceManager();

    log.info("Inside TrackingServlet: process form -------------------");
    ArrayList<Long> selectedMembers = new ArrayList<Long>();
    ArrayList<Long> selectedLocations = new ArrayList<Long>();
    List<String> selectedComboId = new ArrayList<String>();
    
    response.setContentType("text/html");
    Enumeration<?> paramNames = request.getParameterNames();
    request.setAttribute("paramNames", paramNames);
    
    Long deptId = null;
    Long memberId = null;
    Long alertId = null;
    Long locationId = null;
    Long targetLocationId = null;

    while(paramNames.hasMoreElements()) {
      log.info("paramNames Loop Members------------------");

      String paramName = (String)paramNames.nextElement();
      String[] paramValues = request.getParameterValues(paramName);

      if (paramValues.length >= 1) {
//        System.out.println("paramNames||Values: " + paramName + "||" + paramValues );
        
        String paramValue = paramValues[0];
        if (paramName.matches("deptId")) {
          deptId = Long.valueOf(paramValue);
          System.out.println("deptId: " + deptId.toString());
          
        } else if (paramName.matches("alertId") ) {
            alertId = Long.valueOf(paramValue);
            System.out.println("alertId: " + alertId.toString());
          
//        } else if (paramName.matches("targetLocationId") ) {
//            targetLocationId = Long.valueOf(paramValue);
//            System.out.println("targetLocationId: " + locationId.toString());
//          
        } else if (paramName.matches("comboId")) {
          for (int i=0; i < paramValues.length; i++) {  
            String comboId = String.valueOf(paramValues[i]);
            if (comboId != null ) {
              selectedComboId.add(comboId);
            }
            System.out.println("comboId: " + comboId.toString()); }
          
        } else if (paramName.matches("memberId")) {
          for (int i=0; i < paramValues.length; i++) {  
            memberId = Long.valueOf(paramValues[i]);
            selectedMembers.add(memberId);  
            System.out.println("memberId: " + memberId.toString());}
          
        } else if (paramName.matches("locationId")) {
          for (int i=0; i < paramValues.length; i++) {  
            locationId = Long.valueOf(paramValues[i]);
            selectedLocations.add(locationId);  
            System.out.println("locationId: " + locationId.toString());}
        }
      }
    }
    
    if (selectedMembers.isEmpty() && selectedComboId.isEmpty()) {
    	try {
    		response.sendRedirect("noSuchObject.jsp?errorMessage=missingMemberSelection");
    	} catch (IOException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}
    }
    
    if (locationId == null && selectedComboId.isEmpty()) {
    	try {
    		response.sendRedirect("noSuchObject.jsp?errorMessage=missingLocationSelection");
    	} catch (IOException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}
    }
    
    if (selectedMembers.isEmpty() && selectedComboId.isEmpty() && targetLocationId == null)  {
      try {
        response.sendRedirect("noSuchObject.jsp?errorMessage=missingEverything");
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  
    // members
    
    for (int j=0; j < selectedMembers.size(); j++) {
      selectedMembers.get(j);
      System.out.println("Selected Member: " + selectedMembers.get(j));
      Member m = pm.getObjectById(Member.class, selectedMembers.get(j));      
      if (m != null) {
      m.settargetObjectType("Location");
      m.settargetObjectId(locationId);
      pm.makePersistent(m);
      }
      
      if (responseType == null) {
        responseType = "none";
      }
      
      if (locationId != null) {
        Tracking t1 = new Tracking (
          deptId,
          alertId,
          locationId,
          System.currentTimeMillis(),
          null, 
          "member",
          Long.valueOf(selectedMembers.get(j)),
          null,
          responseType
          );
        pm.makePersistent(t1);
      }
    }
    
//    // LOCATIONS (MOVING TO NEW TARGET LOCATION)
//    for (int k=0; k < selectedMembers.size(); k++) {
//      selectedLocations.get(k);
//      Location loc = pm.getObjectById(Location.class, selectedLocations.get(k));
//      if (loc != null) {
//      loc.settargetObjectType("Location");
//      loc.settargetObjectId(locationId);
//      pm.makePersistent(loc);
//      }
//    Tracking t2 = new Tracking (
//      deptId,
//      alertId,
//      locationId,
//      System.currentTimeMillis(),
//      null,  // TODO: johnreilly authorId tbd
//      "location",
//      selectedMembers.get(k),
//      null
//      );
//    pm.makePersistent(t2);
//    }
    
    // locations
    
    for (int s=0; s < selectedComboId.size(); s++) {
      System.out.println("selectedComboId qty: " + selectedComboId.size());
      
      if (!selectedComboId.get(s).equalsIgnoreCase("pending")) {
      
        // parse combo id
        System.out.println("selectedComboId: " + selectedComboId.get(s).toString());
        int delimiter = selectedComboId.get(s).indexOf("|");
        System.out.println("delimiter: " + delimiter);
        int length = selectedComboId.get(s).length();
        System.out.println("length: " + length);
        Long tempLocationId = Long.valueOf(selectedComboId.get(s).substring(0, delimiter));
        System.out.println("locId: " + tempLocationId);
        Long tempStatusId = Long.valueOf(selectedComboId.get(s).substring(delimiter + 1, length ));
        System.out.println("statId: " + tempStatusId);
        
        Tracking t2 = new Tracking (
          deptId,
          alertId,
          tempLocationId,
          System.currentTimeMillis(),
          null,  // TODO: authorId tbd
          "locstat",
          tempStatusId,
          null,  // TODO: Status to be deprecated...
          responseType
          );
        pm.makePersistent(t2);
      }
    }
    pm.close();
    
    System.out.println("Member array size: " + selectedMembers.size());
    System.out.println("DeptId string: " + deptId.toString());
    System.out.println("Leaving TrackingServlet:memberForm ------------------");
    
    RequestDispatcher dispatcher = 
    	getServletContext().getRequestDispatcher("/reportingPrep?deptId=" + deptId.toString() 
        + "&alertId=" + alertId.toString() + "&intent=" + intent);
    try {
			dispatcher.forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
  

}


